/**
 * @desc: 新增组合商品弹框
 */

 import React, { useState, useEffect, useRef } from 'react';
 import CommonModal from '@/components/CommonModal';
 import CommonImgsLoad from '@/components/CommonImgsLoad';
 import CommonTable from '@/components/CommonTable';
 import CommonLoading from '@/components/CommonLoading';
 import AddGoods from './AddGoods';
 import CommonZjfImg from '@/components/CommonImg/ZifComponent';
 import CommonPlatImg from '@/components/CommonImg/PlatformComponent';
 import CommonSysImg from '@/components/CommonImg/SysComponent';
 import CommonTag from '@/components/CommonTag';
 import { Button, Input, Form, Alert, InputNumber, Popconfirm, message, Select } from 'antd';
 import { addGoods, updateGoods, queryTypeChannel } from '@/services/common';
 import { formatWeight, formatAmount } from '@/utils/utils.jsx';
 import { getCurrentUser } from '@/utils/authority';
 import styles from './index.module.less';

 const { Option } = Select;

 //获取渠道类型
 const getChannelType = (arr) => {
	 if (arr.length == 0) {
		 return null;
	 }
	 const list = arr.map(v => v.deliverType);
	 if (list.includes(3)) {
		 if (list.includes(4)) {
			 return null;
		 } else {//库存加拿货
			 return 1;
		 }
	 } else {
		 if ((list.includes(1) || list.includes(2)) && !list.includes(4)) {
			 let btn = false;
			 for (let i in arr) {
				 if (arr[i].isCarefullySelected != 1) {
					 btn = true;
					 break;
				 }
			 }
			 if (btn) {//都是严选商品
				 return 8;
			 } else {
				 return 7;
			 }
		 } else {//都是供应商直发
			 let btn = false;
			 for (let i in arr) {
				 if (arr[i].storeId != arr[0].storeId) {
					 btn = true;
					 break;
				 }
			 }
			 if (btn) {
				 return null;
			 } else {//同一供应商的供应商直发
				 return 0;
			 }
		 }
	 }
 }
 
 const AddCombinaGoods = ({ modalInfo, handleCancel, handleOk }) => {
 
	 const { visible, title, item = {}, } = modalInfo;

	 //记录当前的type值，用以请求发货渠道；
	 let channelType;
 
	 const {
		 composeName,
		 composePrice,
		 composeImage,
		 composeGoodsDetails = [],
		 id = null,
		 channelId,
         code
	 } = item;
 
	 //添加的商品信息
	 const [goodsList, setGoodsList] = useState([]);
 
	 const [scrollKey, setScrollKey] = useState(1);
 
	 const scrollEnd = useRef(null);
 
	 const [goodsVisible, setGoodsVisible] = useState(false);
 
	 const [channelList, setChannelList] = useState([]);
 
	 //获取渠道下拉列表
	 const getChannelList = async (val) => {
		 const type = getChannelType(val);
		 if (type && channelType != type) {
			 channelType = type;
			 setLoading(true);
			 const { data, success } = await queryTypeChannel({
				 isDeleted: 0,
				 type,
				 uuid: getCurrentUser().uuid,
			 })
			 setLoading(false);
			 if (success) {
				 setChannelList(data)
			 }
		 } else {
			 if (type == 0) {
				 const arr = [
					 { id: 0, channelName: `${val[0].storeName}(直发)` }
				 ]
				 setChannelList(arr);
			 }
		 }
	 }
 
	 //处理商品信息
	 const handleGoodsList = val => {
		 const arr = [];
		 val.map(v => {
			 if (v.deliverType == 3) {
				 if (v.goodsShowType == 1) {//系统
					 arr.push({
						 productId: v.productId,
						 productType: v.productType,
						 skuName: v.goodsSpec,
						 goodsName: v.goodsName,
						 goodsImage: v.goodsImage,
						 isCarefullySelected: v.isCarefullySelected,
						 storeId: v.type == 3 ? v.zjfStoreId: v.storeId,
						 storeName: v.storeName,
						 deliverType: v.deliverType,
						 goodsNum: v.goodsNum,
						 goodsWeight: v.goodsWeight,
						 goodsId: v.goodsId,
                         skuId: v?.skuId,
						 goodsPrice: v.goodsPrice,
						 type: v.type,
						 goodsCommonId: v.zjfGoodsCommonId,
						 customType: 'sys',
                         price: v.zjfGoodsPrice,
					 })
				 } else {//网店
					 arr.push({
						 productId: v.productId,
						 productType: v.productType,
						 ecSkuName: v.goodsSpec,
						 ecGoodsImage: v.goodsImage,
						 ecGoodsName: v.goodsName,
						 isCarefullySelected: v.isCarefullySelected,
						 storeId: v.type == 3 ? v.zjfStoreId: v.storeId,
						 storeName: v.storeName,
						 deliverType: v.deliverType,
						 goodsNum: v.goodsNum,
						 ecGoodsWeight: v.goodsWeight,
						 goodsId: v.goodsId,
                         outStoreSku: v?.outStoreSku,
						 ecGoodsPrice: v.goodsPrice,
						 type: v.type,
						 goodsCommonId: v.zjfGoodsCommonId,
						 customType: 'shop',
                         price: v.zjfGoodsPrice,
					 })
				 }
			 } else {
				 arr.push({
					 productId: v.productId,
					 productType: v.productType,
					 goodsSpec: v.zjfGoodsSpec,
					 goodsImage: v.zjfGoodsImage,
					 goodsName: v.zjfGoodsName,
					 isCarefullySelected: v.isCarefullySelected,
					 storeId: v.zjfStoreId,
					 storeName: v.zjfStoreName,
					 deliverType: v.deliverType,
					 goodsNum: v.goodsNum,
					 goodsWeight: v.zjfGoodsWeight,
					 goodsId: v.zjfGoodsId,
                     zjfGoodsId: v?.zjfGoodsId,
					 type: v.type,
					 goodsPrice: v.zjfGoodsPrice,
					 vipPrice: v.vipPrice,
					 goodsCommonId: v.zjfGoodsCommonId,
					 customType: 'zjf',
                     price: v.zjfGoodsPrice,
				 })
			 }
		 })
		 return arr;
	 }
 
	 useEffect(() => {
		 if (visible) {
			 if (item.id || composeGoodsDetails.length > 0) {
				 setGoodsList(handleGoodsList(composeGoodsDetails));
				 handleCountPrice(composeGoodsDetails);
				 getChannelList(handleGoodsList(composeGoodsDetails));
				 form.setFieldsValue({
					 composeImage: composeImage,
					 composePrice: composePrice || 0,
					 composeName: composeName,
					 channelId: channelId,
                     code: code
				 });
			 }
		 }
	 }, [visible]);
 
	 const [loading, setLoading] = useState(false);
 
	 const [form] = Form.useForm();
 
	 const columns = [
		 {
			 title: '供应商名称',
			 dataIndex: 'storeName',
			 key: 'storeName',
			 width: '15%',
			 render: (_, record) => {
				 if (record.customType == 'sys') {
					 return <span className="table-weight-text">系统商品</span>;
				 } else {
					 return <span className="table-weight-text">{record.storeName}</span>
				 }
			 },
		 },
		 {
			 title: '商品',
			 width: '40%',
			 dataIndex: 'goodsName',
			 key: 'goodsName',
			 render: (_, record) => {
	            const newCode = record?.customType == 'sys' ? record?.skuId : record?.customType == 'shop' ? record?.outStoreSku : record?.goodsId;
				 return (
					 <div style={{ display: 'flex', alignItems: 'center' }}>
						 {record.customType == 'shop' && <CommonPlatImg img={record.ecGoodsImage} style={{ marginRight: '8px' }} />}
						 {record.customType == 'sys' && <CommonSysImg img={record.goodsImage} isCloudIcon={record.isCarefullySelected} storeId={record.storeId} style={{ marginRight: '8px' }} />}
						 {
							 record.customType == 'zjf' && <CommonZjfImg img={record.goodsImage} isCloudIcon={record.isCarefullySelected} storeId={record.storeId} style={{ marginRight: '8px' }} />
						 }
						 <div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
							 {
								 record.customType == 'shop' &&
								 <>
									 <span>{record.ecGoodsName}{record.ecSkuName}</span>
									 <span className="common-color9">¥{formatAmount(record.ecGoodsPrice)}</span>
								 </>
							 }
							 {
								 record.customType == 'sys' &&
								 <>
									 <span>{record.goodsName}{record.skuName}</span>
									 <span className="common-color9">¥{formatAmount(record.goodsPrice)}</span>
								 </>
							 }
							 {
								 record.customType == 'zjf' &&
								 <>
									 <span>{record.goodsName}{record.goodsSpec}</span>
									 <span className="common-color9">¥{record.vipPrice ? formatAmount(record.vipPrice) : formatAmount(record.goodsPrice)}</span>
								 </>
							 }
                             <div style={{display: 'flex'}}><span>商品编码：</span><span className='textOverflowMultiOne'>{newCode}</span></div>
							 <span>
								 {(record.deliverType == 1 || record.deliverType == 2) && <CommonTag type='nahuo' />}
								 {record.deliverType == 3 && <CommonTag type='zifa' />}
								 {record.deliverType == 4 && <CommonTag type='cjzf' />}
							 </span>
						 </div>
					 </div>
				 );
			 },
		 },
		 {
			 title: '单件重量(kg)',
			 width: '15%',
			 dataIndex: 'goodsWeight',
			 key: 'goodsWeight',
			 render: (_, record) => {
				 if (record.customType == 'shop') {
					 return formatWeight(record.ecGoodsWeight);
				 }
				 return formatWeight(record.goodsWeight);
			 }
		 },
		 {
			 title: '数量(个)',
			 width: '15%',
			 dataIndex: 'goodsNum',
			 key: 'goodsNum',
			 render: (text, _, index) => (
                 <div className={styles.noInputButton}>
                  <InputNumber
					 min={1}
					 value={text}
					 onBlur={(e) => handleNumChange(e, index)}
				 />
                 </div>

			 ),
		 },
		 {
			 title: '操作',
			 width: '15%',
			 key: 'opera',
			 render: (text, record, index) => (
				 <span className="opera-span-common">
					 <Popconfirm
						 title="确定删除?"
						 onConfirm={() => handleDeleteGoods(index)}
						 okText="确定"
						 cancelText="取消"
					 >
						 <span>删除</span>
					 </Popconfirm>
				 </span>
			 ),
		 },
	 ];
 
	 //计算组合商品的价格
	 const handleCountPrice = (val) => {
		 if (val.length == 0) {
			 form.setFieldsValue({
				 composePrice: 0,
			 });
		 } else {
			 let sum = 0;
			 for (let i in val) {
				 const obj = val[i];
				 const { goodsNum, customType } = obj;
				 let price;
				 if (customType == 'shop') {
					 price = obj.ecGoodsPrice || 0;
				 } else if (customType == 'zjf') {
					 if (obj.vipPrice || obj.vipPrice == 0) {
						 price = obj.vipPrice;
					 } else {
						 price = obj.goodsPrice;
					 }
				 } else {
					 price = obj.goodsPrice;
				 }
				 sum += price * goodsNum;
			 }
			 form.setFieldsValue({
				 composePrice: sum.toFixed(2),
			 });
		 }
	 };
 
	 //删除商品
	 const handleDeleteGoods = (index) => {
		 const arr = [...goodsList];
		 arr.splice(index, 1);
		 setGoodsList(arr);
		 handleCountPrice(arr);
		 const type = getChannelType(arr);
		 if(type !== channelType ) {
			 setChannelList([]);
			 form.setFieldsValue({ channelId: undefined });
		 }
		 getChannelList(arr);
	 };
 
	 //更改商品数量
	 const handleNumChange = (e, index) => {
		 const val = e.target.value;
         const reg = /^[1-9]\d*$/;
		 if (val == goodsList[index].goodsNum) {
			 return;
		 }
         if(reg.test(val)) {
            const arr = [...goodsList];
            arr[index].goodsNum = val;
            setGoodsList(arr);
            handleCountPrice(arr);
         } else {
             message.info('请输入正整数')
         }
	 };
 
	 //添加商品
	 const handleAddGoods = () => {
		 setGoodsVisible(true);
	 };
 
	 //滚动到底部
	 const handleScroll = () => {
		 if (scrollEnd.current && scrollKey > 1) {
			 const scrollHeight = scrollEnd.current.scrollHeight; //里面div的实际高度
			 const height = scrollEnd.current.clientHeight; //网页可见高度
			 const maxScrollTop = scrollHeight - height;
			 scrollEnd.current.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
			 //如果实际高度大于可见高度，说明是有滚动条的，则直接把网页被卷去的高度设置为两个div的高度差，实际效果就是滚动到底部了。
		 }
	 };
 
	 useEffect(() => {
		 handleScroll();
	 }, [scrollKey]);
 
	 //提交校验
	 const handleVailtyGoods = () => {
		 if (goodsList.length < 1) {
			 message.error('未选择商品');
			 return;
		 } else {
			 handleSubmit();
		 }
	 };
 
	 //提交
	 const handleSubmit = () => {
		 form
			 .validateFields()
			 .then((val) => {
				 onOk(val);
			 })
			 .catch((info) => {
				 form.scrollToField('composeName');
				 //console.log('Validate Failed:', info);
			 });
	 };
 
	 //校验成功，提交数据
	 const onOk = async (val) => {
		 const arr = [];
		 goodsList.map(v => {
			 arr.push({
				 deliverType: v.deliverType,
				 goodsCommonId: v.goodsCommonId,
				 goodsId: v.goodsId,
				 storeId: v.storeId,
				 goodsNum: v.goodsNum,
				 productId: v.productId,
				 productType: v.productType,
				 type: v.type,
				 price: v.price,
			 })
		 })
		 setLoading(true);
		 let res;
		 if (id != 0 && !id) {
			 //如果id不存在，走的是新增接口（包含复制）
			 res = await addGoods({
				 ...val,
				 goodsDtoS: arr,
			 });
			 if (res.success) {
                form.resetFields();
                handleOk();
				 message.success('添加成功！');
			 }
		 } else {
			 //走更新接口
			 res = await updateGoods({
				 id,
				 ...val,
				 goodsDtoS: arr,
			 });
			 if (res.success) {
                form.resetFields();
                handleOk();
				 message.success('更新成功！');
			 }
		 }
		 setLoading(false);
	 };
 
	 //图片上传回调手动更新表单值
	 const handleDone = (val) => {
		 form.setFieldsValue({
			 composeImage: val,
		 });
	 };
 
	 //取消事件。重置数据
	 const onCancel = () => {
		 form.resetFields();
		 setGoodsList([]);
		 setLoading(false);
		 handleCancel();
	 };
 
	 const handleGetChannel = (val) => {
		 if (val) {
			 getChannelList(goodsList);
		 }
	 }
 
 
	 const CommonTableProps = {
		 data: goodsList,
		 columns,
		 size: 'small',
		 rowkey: 'goodsId',
	 };
 
	 const AddGoodsProps = {
		 visible: goodsVisible,
		 item: goodsList,
		 handleOk(val) {
			 const arr = [...goodsList, ...val];
			 setGoodsList(arr);
			 handleCountPrice(arr);
			 setScrollKey(scrollKey + 1);
			 setGoodsVisible(false);
			 const type = getChannelType(arr);
			 if(type !== channelType) {
				 setChannelList([]);
				 form.setFieldsValue({ channelId: undefined });
			 }
			 getChannelList(arr);
		 },
		 handleCancel() {
			 setGoodsVisible(false);
		 },
	 };
 
	 const optionChannel = channelList.map(item => {
		 return <Option key={item.id} value={item.id}>{item.channelName}{item.id == 0 ? null : getCurrentUser().uuid == item.uuid ? '(自发)' : '(第三方)'}</Option>
	 })
 
	 return (
		 <CommonModal
			 title={title}
			 visible={visible}
			 onCancel={onCancel}
			 width="848px"
			 overflowY='hidden'
			 footer={[
				 <Button key="back" onClick={onCancel}>
					 取消
				 </Button>,
				 <Button key="save" type="primary" onClick={handleVailtyGoods}>
					 保存
				 </Button>,
			 ]}
		 >
			 <div ref={scrollEnd} style={{ maxHeight: '546px', overflow: 'auto'} }>
				 <Alert
					 style={{ marginBottom: 16 }}
					 message="建议组合商品与第三方平台信息保持一致，方便商品信息匹配，尤其注意商品名称的可识别性！ "
					 type="info"
				 />
				 <Form
					 onFinish={handleSubmit}
					 form={form}
					 name="add-combina-goods"
					 initialValues={{
						 composeImage: composeImage,
						 composePrice: composePrice || 0,
						 composeName: composeName,
						 channelId: channelId,
                         code: code
					 }}
				 >
					 <Form.Item
						 extra="如：通用床品5件套--岁月静好"
						 name="composeName"
						 label="组合商品名称"
						 rules={[
							 { required: true, message: '组合商品名称未填写' },
							 { max: 60, message: '最多支持输入60个字符' },
						 ]}
					 >
						 <Input style={{ width: 'px' }} placeholder="请输入组合商品名称" />
					 </Form.Item>
					 <Form.Item
						 name="composePrice"
						 label="组合商品价格"
						 rules={[{ required: true, message: '组合商品价格未填写' }]}
					 >
						 <Input style={{ width: '120px' }} disabled />
					 </Form.Item>
					 <Form.Item
						 extra="图片建议与第三方平台保存一致"
						 rules={[{ required: true, message: '组合商品图片未上传' }]}
						 name="composeImage"
						 label="组合商品图片"
					 >
						 <CommonImgsLoad img={composeImage} handleOk={handleDone} />
					 </Form.Item>
                      <Form.Item
						 name="code"
						 label="组合商品编号"
                         rules={[
                            { required: true, message: '组合商品编号未填写' },
                            { max: 50, message: '最多支持输入50个字符' },
                        ]}
					 >
						 <Input />
					 </Form.Item>
					 <Form.Item
						 label="发货渠道"
						 name="channelId"
						 rules={[
							 { required: true, message: '请选择发货渠道' },
						 ]}
					 >
						 <Select size='small' onDropdownVisibleChange={handleGetChannel} placeholder="请选择发货渠道" style={{ width: '260px' }}>
							 {optionChannel}
						 </Select>
					 </Form.Item>
				 </Form>
				 <Alert
					 message={
						 <div>
							 <p>
								 1、组合商品的第一商品，建议设置为第三方平台组合商品的主商品，方便检查核对！
							 </p>
							 <p>
								 2、云仓严选商品与非云仓严选商品，由于目前不支持同一个仓库发货，建议不要添加在同一个组合里
							 </p>
						 </div>
					 }
					 type="warning"
				 />
				 <Button onClick={handleAddGoods} style={{ margin: '12px 0' }}>添加商品</Button>
				 <CommonTable {...CommonTableProps} style={{ marginBottom: '24px' }} />
				 <CommonLoading loading={loading} />
				 {goodsVisible && <AddGoods {...AddGoodsProps} />}
			 </div>
 
		 </CommonModal>
	 );
 };
 
 export default AddCombinaGoods;
 
